<?php
session_start();

// 数据库连接信息
include 'config.php';
// 获取当前用户
$current_user = $_SESSION['username'] ?? '';

// 检查是否已经登录
if (empty($current_user)) {
    echo json_encode(['status' => 'error', 'message' => '您尚未登录']);
    exit;
}

// 获取用户提交的表单数据
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $old_password = md5($_POST['old_password'] ?? ''); // 原密码（MD5加密）
    $new_password = md5($_POST['new_password'] ?? ''); // 新密码（MD5加密）

    // 查询数据库验证原密码
    $stmt = $conn->prepare("SELECT password FROM admin WHERE username = ?");
    $stmt->bind_param("s", $current_user);
    $stmt->execute();
    $stmt->bind_result($db_password);
    $stmt->fetch();
    $stmt->close();

    // 如果原密码匹配
    if ($db_password === $old_password) {
        // 更新密码
        $stmt = $conn->prepare("UPDATE admin SET password = ? WHERE username = ?");
        $stmt->bind_param("ss", $new_password, $current_user);
        if ($stmt->execute()) {
            // 密码更新成功，使所有Cookie失效并重定向
            if (isset($_SERVER['HTTP_COOKIE'])) {
                $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
                foreach ($cookies as $cookie) {
                    $parts = explode('=', $cookie);
                    $name = trim($parts[0]);
                    setcookie($name, '', time() - 1000);
                    setcookie($name, '', time() - 1000, '/');
                }
            }
            // 销毁会话
            session_destroy();
            // 重定向到登录页面或其他页面
            header('Location: ../login.php'); // 假设登录页面为 ../login.php
            exit;
        } else {
            echo json_encode(['status' => 'error', 'message' => '密码更新失败，请稍后再试']);
        }
        $stmt->close();
    } else {
        echo json_encode(['status' => 'error', 'message' => '原密码错误']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => '非法请求']);
}

$conn->close();
?>
